using System;
using System.Collections.Generic;
using System.Globalization;
using System.Data;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPSolutions.Samples.PickerApp.WebControls
{
    /// <summary>
    /// Represents a site query control
    /// </summary>
    public class CityQueryControl : PickerQueryControlBase
    {
        /// <summary>
        /// Result control
        /// </summary>
        public TableResultControl ResultControl
        {
            get { return (TableResultControl)base.PickerDialog.ResultControl; }
        }

        /// <summary>
        /// Editor control
        /// </summary>
        public CityEditor EditorControl
        {
            get { return (CityEditor)base.PickerDialog.EditorControl; }
        }

        /// <summary>
        /// Get requested state
        /// </summary>
        public string RequestedState
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["State"]))
                {
                    return "TN";
                }
                return Page.Request.QueryString["State"];
            }
        }

        /// <summary>
        /// OnPreRender method
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            base.ColumnList.Visible = false;
        }

        /// <summary>
        /// Create a datatable
        /// </summary>
        /// <returns></returns>
        private DataTable CreateDataTable()
        {
            // Method variables
            DataColumn column;

            // Init data table
            DataTable table = new DataTable();
            table.Locale = CultureInfo.InvariantCulture;

            // Loop visible column names
            foreach (string columnName in ResultControl.ColumnNames)
            {
                column = new DataColumn();
                column.DataType = typeof(string);
                column.ColumnName = columnName;
                table.Columns.Add(column);
            }

            // Loop additional columns
            string[] hiddenColumnNames = new string[] { CityEditor.CityInfo.CityId };
            foreach (string columnName in hiddenColumnNames)
            {
                column = new DataColumn();
                column.DataType = typeof(string);
                column.ColumnName = columnName;
                table.Columns.Add(column);
            }

            // Return table
            return table;
        }

        /// <summary>
        /// Get entity from row
        /// </summary>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        public override PickerEntity GetEntity(DataRow dataRow)
        {
            // No datarow provided
            if (dataRow == null)
                return null;

            // Create new picker
            PickerEntity entity = new PickerEntity();
            entity.Key = Convert.ToString(dataRow[CityEditor.CityInfo.CityId]);
            entity.DisplayText = Convert.ToString(dataRow[CityEditor.CityInfo.Title]);
            entity.Description = Convert.ToString(dataRow[CityEditor.CityInfo.State]);
            entity.IsResolved = true;

            // Add extended data
            entity.EntityData.Clear();
            entity.EntityData.Add(
                CityEditor.CityInfo.State, 
                dataRow[CityEditor.CityInfo.State]);
            return entity;
        }

        /// <summary>
        /// Get matching webs
        /// </summary>
        /// <param name="search"></param>
        /// <param name="group"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        protected override int IssueQuery(string search, string group, 
            int pageIndex, int pageSize)
        {
            // Trim search
            search = (search != null) ? search.Trim() : null;

            #region No search provided error
            
            // Ensure search value
            if (string.IsNullOrEmpty(search))
            {
                PickerDialog.ErrorMessage = "No search provided";
                return 0;
            }

            #endregion

            // Get site with elevation
            City[] matchingCities = CityManager.AllCities.GetMatchingCities(search);

            #region No cities found error

            // No matches found
            if (matchingCities == null || matchingCities.Length == 0)
            {
                PickerDialog.ErrorMessage = "No matching cities found.";
                return 0;
            }

            #endregion

            // Create table
            DataTable table = CreateDataTable();
            DataRow row;

            // Create rows
            foreach (City city in matchingCities)
            {
                // Create new row
                row = table.NewRow();

                // Add data to row
                row[CityEditor.CityInfo.CityId] = city.Name;
                row[CityEditor.CityInfo.Title] = city.Name;
                row[CityEditor.CityInfo.State] = city.State;

                // Add row to table
                table.Rows.Add(row);
            }

            // Return results to dialog
            PickerDialog.Results = table;
            PickerDialog.ResultControl.PageSize = table.Rows.Count; 

            // Return number of records
            return table.Rows.Count;
        }

    }
}
